import { Component, OnInit } from '@angular/core';

import { Hero } from '../hero';
import { HEROES } from '../mock-heroes';

import { HeroService } from '../hero.service';
import { Observable } from 'rxjs';
import { MessageService } from '../message.service';


@Component({
    selector: 'app-heroes',
    templateUrl: './heroes.component.html',
    styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {

    //#region 字段
    /**
     * 选中的英雄
     */
    selectedHero: Hero;
    /**
     * 英雄列表
     */
    heroes: Hero[];
    //#endregion

    constructor(private service: HeroService, private messageService: MessageService) { }

    ngOnInit() {
        // this.heroes = this.getHeroes();
        this.getHeroesAsync()
            .subscribe(t => {
                this.heroes = t;
            });
    }

    /**
     * 呈现选中的英雄
     * @param hero 英雄
     */
    onSelect(hero: Hero): void {
        if (this.selectedHero === hero) {
            return;
        }

        if (this.selectedHero !== hero) {
            this.messageService.add('选中：' + hero.name);
            this.selectedHero = hero;
        }
    }

    /**
     * 获取英雄列表
     */
    getHeroesAsync(): Observable<Hero[]> {
        return this.service.getHeoresAsync();
    }

    addHero(name: string) {
        if (!name) { return; }
        name = name.trim();
        const h = { name };
        this.service
            .addHeroAsync(h as Hero)
            .subscribe(t => {
                this.heroes.push(t);
                name = null;
            });
    }

    deleteHero(hero: Hero) {
        this.service
            .deleteHeroAsync(hero)
            .subscribe(
                _ => this.heroes = this.heroes.filter(h => h.id !== hero.id)
            );
    }
}
